package com.wookii.friedeggs.ui.home

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.input.input
import com.bw.base.tool.longToast
import com.wookii.friedeggs.MainViewModel
import com.wookii.friedeggs.MainViewModelFactory
import com.wookii.friedeggs.MyApplication
import com.wookii.friedeggs.R
import com.wookii.friedeggs.data.Student
import com.wookii.friedeggs.databinding.FragmentHomeBinding
import kotlinx.coroutines.Dispatchers

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!


    //通过ViewModelFactory初始化ViewModel
    private val viewModel: MainViewModel by activityViewModels {
        val studentDao = (activity?.application as MyApplication).database.studentDao()
        val examDao = (activity?.application as MyApplication).database.examDao()
        val classDao = (activity?.application as MyApplication).database.classDao()

        MainViewModelFactory(studentDao, examDao, classDao)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val homeViewModel =
            ViewModelProvider(this)[HomeViewModel::class.java]

        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root

        val textView: TextView = binding.textHome
        homeViewModel.text.observe(viewLifecycleOwner) {
            textView.text = it
        }
        val studentsListAdapter =
            StudentsListAdapter(mutableListOf()) { student: Student ->

            }
        binding.studentList.apply {
            layoutManager = GridLayoutManager(requireContext(), 4)
            adapter = studentsListAdapter
        }
        //查询并监听考试表里学生的变化
        viewModel.getUnFinishExam().asLiveData().observe(viewLifecycleOwner) {
            if (it.isEmpty()) return@observe
            studentsListAdapter.data = it[0].students as MutableList<Student>
            studentsListAdapter.notifyDataSetChanged()
            binding.textHome.visibility = View.GONE
            //班级名称
            binding.className.text = it[0].exam.classInfo?.className
        }
        viewModel.examFlow.asLiveData(Dispatchers.Main).observe(viewLifecycleOwner) {
            //更新班级名称
            longToast(it.classInfo?.className ?: "")
            binding.className.text = it.classInfo?.className ?: ""
        }
        viewModel.showClassDialog.observe(viewLifecycleOwner) {
            //展示dialog
            showChangeClassName()
        }
        return root
    }

    @SuppressLint("CheckResult")
    private fun showChangeClassName(mPrefill: String? = null) {
        MaterialDialog(requireActivity()).show {
            cornerRadius(16f)
            input(maxLength = 15, hintRes = R.string.class_hint, prefill = mPrefill) { _, text ->
                Log.i("input_text", text.toString())
                //更新考试表，把班级信息更新
                viewModel.updateExamClassName(text)
            }
            positiveButton(R.string.submit)
            negativeButton(R.string.cancel)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}